<template>
  <div style="width: 800px; margin: auto">
    <h1>登录</h1>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          Create
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        <el-button type="primary" @click="showSaveDiv()">注册</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-dialog v-model="dialogVisible" title="Tips" width="500">
        <template #footer>
          <el-form
            ref="ruleFormRefSave"
            style="max-width: 600px"
            :model="saveData"
            :rules="rulesSave"
            label-width="auto"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="saveData.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="saveData.password" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="saveData.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="saveData.email" />
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="saveData.realName" />
            </el-form-item>
            <el-form-item style="margin-left: 100px">
              <el-button
                type="primary"
                @click="submitFormSave(ruleFormRefSave)"
              >
                提交
              </el-button>
              <el-button @click="resetFormSave(ruleFormRefSave)"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { login, registerService } from "../api/api";
import { useRouter } from "vue-router";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
interface RuleForm {
  username: string;
  password: string;
}
const ruleForm = reactive<RuleForm>({
  username: "",
  password: "",
});

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: "请输入账号！", trigger: "blur" },
    { min: 3, max: 5, message: "长度必须是 3-5 位", trigger: "blur" },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      login(ruleForm).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("登录成功！");
          let user = res.data.data;
          let token = user.token;
          sessionStorage.setItem("token", token);
          sessionStorage.setItem("user", JSON.stringify(user));
          router.push("/home");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
const dialogVisible = ref(false);
const ruleFormRefSave = ref<FormInstance>();
const showSaveDiv = () => {
  dialogVisible.value = true;
};
const saveData = ref({
  email: "",
  password: "",
  phone: "",
  realName: "",
  username: "",
});
const rulesSave = reactive<FormRules>({
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 6, max: 12, message: "用户名长度至少 6-12 位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    {
      pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$/,
      message: "密码不能小于6位,且必须包含字母,数字和大写字母",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "手机号格式错误",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    {
      pattern: /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
      message: "邮箱格式错误",
      trigger: "blur",
    },
  ],
  realName: [
    { required: true, message: "真实姓名不能为空", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5]+$/,
      message: "真实姓名必须为汉字",
      trigger: "blur",
    },
  ],
});

const submitFormSave = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      registerService(saveData.value).then((res) => {
        if (res.data.flag) {
          ElMessage.success("注册成功");
          dialogVisible.value = false;
        } else {
          ElMessage.error(res.data.mag);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetFormSave = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options1 = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>
